﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Core.Interfaces;
using Core.Interfaces.IDAO;
using Core.Interfaces.IPresenters;
using Core.Unity;
using Microsoft.Practices.Unity;

namespace Core.Presenters
{
    public class DistrictPresenter
    {
        private IDistrictDAO _districtDAO;
        private IDistrict _district;
        private IDistrictView _districtView;
        private List<IDistrict> _districts; 

        public DistrictPresenter(IDistrictView districtView, IDistrict district = null)
        {
            _districtDAO = ResolverContainer.Resolver.Resolve<IDistrictDAO>();
            _district = district ?? ResolverContainer.Resolver.Resolve<IDistrict>();
            districtView.District.DataSource = _district;
            districtView.SaveDistrict += SaveDistrict;
            _districtView = districtView;
            _districts = _districtDAO.GetAll(false);
            districtView.ShowDialog();
            
        }

        private void SaveDistrict(object sender, EventArgs eventArgs)
        {
            if(!_districts.Any(x=> x.Name.Equals(_district.Name)))
            { if (_districtDAO.SaveOrUpdateAndCommit(_district))
              {
                _districtView.Close();
              }
            }
            else
            {
                MessageBox.Show("Такой район уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1);
            }
        }
    }
}
